import { useEffect, useCallback, useRef } from 'react'
import { performanceMonitor, type PerformanceMetrics } from '../utils/performance'

export function usePerformance() {
  const startTimes = useRef<Map<string, number>>(new Map())

  const startMeasurement = useCallback((name: string) => {
    startTimes.current.set(name, performance.now())
  }, [])

  const endMeasurement = useCallback((name: string, metadata?: Record<string, any>) => {
    const startTime = startTimes.current.get(name)
    if (startTime) {
      const duration = performance.now() - startTime
      console.log(`${name} took ${duration.toFixed(2)}ms`, metadata)
      startTimes.current.delete(name)
      return duration
    }
    return null
  }, [])

  const measureAsync = useCallback(async <T>(
    name: string,
    asyncFn: () => Promise<T>,
    metadata?: Record<string, any>
  ): Promise<T> => {
    const startTime = performance.now()
    try {
      const result = await asyncFn()
      const duration = performance.now() - startTime
      console.log(`${name} took ${duration.toFixed(2)}ms`, metadata)
      return result
    } catch (error) {
      const duration = performance.now() - startTime
      console.log(`${name} failed after ${duration.toFixed(2)}ms`, metadata, error)
      throw error
    }
  }, [])

  const getMetrics = useCallback(() => {
    return performanceMonitor.getMetrics()
  }, [])

  const getCoreWebVitals = useCallback(() => {
    return performanceMonitor.getCoreWebVitals()
  }, [])

  const getPerformanceScore = useCallback(() => {
    return performanceMonitor.getPerformanceScore()
  }, [])

  return {
    startMeasurement,
    endMeasurement,
    measureAsync,
    getMetrics,
    getCoreWebVitals,
    getPerformanceScore
  }
}

export function useRoutePerformance() {
  const routeStartTime = useRef<number>()

  const startRouteChange = useCallback((route: string) => {
    routeStartTime.current = performance.now()
    console.log(`Starting route change to ${route}`)
  }, [])

  const endRouteChange = useCallback((route: string) => {
    if (routeStartTime.current) {
      performanceMonitor.measureRouteChange(route, routeStartTime.current)
      routeStartTime.current = undefined
    }
  }, [])

  return { startRouteChange, endRouteChange }
}

export function useApiPerformance() {
  const measureApiCall = useCallback((
    url: string,
    method: string = 'GET'
  ) => {
    const startTime = performance.now()
    
    return {
      end: () => {
        performanceMonitor.measureApiCall(url, startTime, method)
      }
    }
  }, [])

  return { measureApiCall }
}

export function useComponentPerformance(componentName: string) {
  const renderStartTime = useRef<number>()

  useEffect(() => {
    // Measure component mount time
    renderStartTime.current = performance.now()
    
    return () => {
      // Measure component unmount time
      if (renderStartTime.current) {
        const mountTime = performance.now() - renderStartTime.current
        console.log(`${componentName} was mounted for ${mountTime.toFixed(2)}ms`)
      }
    }
  }, [componentName])

  useEffect(() => {
    // Measure render time
    if (renderStartTime.current) {
      const renderTime = performance.now() - renderStartTime.current
      console.log(`${componentName} rendered in ${renderTime.toFixed(2)}ms`)
      renderStartTime.current = undefined
    }
  })

  const measureOperation = useCallback((operationName: string, operation: () => void) => {
    const startTime = performance.now()
    operation()
    const duration = performance.now() - startTime
    console.log(`${componentName}.${operationName} took ${duration.toFixed(2)}ms`)
  }, [componentName])

  return { measureOperation }
}
